import os
import json
import zipfile
import shutil
from utils.geo_utils import calculate_total_distance_and_duration
from generators.grid_generator import generate_grid_waypoints
from generators.kml_generator import create_template_kml_content
from generators.wpml_generator import create_waylines_wpml_content
from config.default_config import get_default_flight_parameters

def geojson_to_dji_kmz(input_geojson_path, output_kmz_path, flight_params=None):
    """
    将GeoJSON面数据转换为大疆司空2兼容的KMZ文件
    """
    if flight_params is None:
        flight_params = get_default_flight_parameters()
        
    try:
        # 1. 读取GeoJSON文件
        with open(input_geojson_path, 'r', encoding='utf-8') as f:
            geojson_data = json.load(f)

        if not geojson_data.get('features'):
            print("错误：GeoJSON文件没有 'features' 列表。")
            return False

        # 提取第一个Feature的第一个Polygon的外环坐标
        first_feature = geojson_data['features'][0]
        geometry_type = first_feature.get('geometry', {}).get('type')
        
        raw_coords = []
        if geometry_type == 'Polygon':
            raw_coords = first_feature['geometry']['coordinates'][0] # 外环
        elif geometry_type == 'MultiPolygon':
            raw_coords = first_feature['geometry']['coordinates'][0][0] # 第一个多边形的外环
        else:
            print(f"错误：不支持的几何类型 '{geometry_type}'。请使用Polygon或MultiPolygon。")
            return False

        if not raw_coords:
            print("错误：未能从GeoJSON中提取坐标。")
            return False
            
        # 确保坐标是 [lon, lat] 格式
        template_polygon_coords = [[c[0], c[1], c[2] if len(c) > 2 else flight_params.get("geojson_altitude_offset",0)] for c in raw_coords]
        
        # 生成栅格航线点
        waypoint_coords_lon_lat = generate_grid_waypoints(raw_coords, flight_params)

        # 如果最后一个点和第一个点不同（对于闭合多边形），确保template_polygon_coords闭合
        if template_polygon_coords[0] != template_polygon_coords[-1]:
            template_polygon_coords.append(template_polygon_coords[0])

        # 2. 计算总距离和时长
        total_distance, total_duration = calculate_total_distance_and_duration(waypoint_coords_lon_lat, flight_params['speed'])
        print(f"计算得到的总距离: {total_distance:.2f} 米, 预计总时长: {total_duration:.2f} 秒")

        # 3. 生成 KML 和 WPML 内容
        template_kml_content = create_template_kml_content(template_polygon_coords, flight_params)
        waylines_wpml_content = create_waylines_wpml_content(waypoint_coords_lon_lat, flight_params, total_distance, total_duration)

        # 4. 创建临时文件夹和文件
        temp_dir = "temp_dji_kmz_creation"
        wpmz_dir = os.path.join(temp_dir, "wpmz")
        os.makedirs(wpmz_dir, exist_ok=True)

        with open(os.path.join(wpmz_dir, "template.kml"), 'w', encoding='utf-8') as f:
            f.write(template_kml_content)
        with open(os.path.join(wpmz_dir, "waylines.wpml"), 'w', encoding='utf-8') as f:
            f.write(waylines_wpml_content)

        # 5. 打包成KMZ
        with zipfile.ZipFile(output_kmz_path, 'w', zipfile.ZIP_DEFLATED) as kmz_file:
            # 将wpmz文件夹内的内容添加到KMZ的wpmz路径下
            kmz_file.write(os.path.join(wpmz_dir, "template.kml"), arcname="wpmz/template.kml")
            kmz_file.write(os.path.join(wpmz_dir, "waylines.wpml"), arcname="wpmz/waylines.wpml")
        
        print(f"成功！KMZ文件已生成: {output_kmz_path}")
        return True

    except FileNotFoundError:
        print(f"错误：找不到输入的GeoJSON文件 {input_geojson_path}")
    except json.JSONDecodeError:
        print(f"错误：输入的GeoJSON文件格式无效。")
    except Exception as e:
        print(f"处理过程中发生错误: {e}")
        import traceback
        traceback.print_exc()  # 打印详细错误信息
        return False
    finally:
        # 6. 清理临时文件夹
        if 'temp_dir' in locals() and os.path.exists(temp_dir):
            shutil.rmtree(temp_dir)
    
    return False

def create_example_geojson(file_path):
    """创建示例GeoJSON文件"""
    example_geojson_content = {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "properties": {},
                "geometry": {
                    "type": "Polygon",
                    "coordinates": [
                        [
                            [120.537804, 31.956433],
                            [120.543072, 31.977733],
                            [120.563545, 31.971204],
                            [120.556126, 31.954731],
                            [120.537804, 31.956433] # 确保闭合
                        ]
                    ]
                }
            }
        ]
    }
    
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(example_geojson_content, f, indent=2)
        print(f"提示：已在 {file_path} 创建一个示例GeoJSON文件，请根据需要修改其内容。")
        return True
    except Exception as ex:
        print(f"尝试创建示例GeoJSON文件失败: {ex}")
        return False

def process_geojson_file(input_path=None, output_path=None, params=None):
    """处理GeoJSON文件并转换为KMZ"""
    if input_path is None:
        input_path = "D:/xunJi/python/my/geojsonToKmz/data/test.json"
    
    if output_path is None:
        output_path = "D:/xunJi/python/my/geojsonToKmz/output/test.kmz"
    
    # 确保输出目录存在
    output_dir = os.path.dirname(output_path)
    if output_dir and not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 如果输入文件不存在，则创建示例文件
    if not os.path.exists(input_path):
        print(f"错误：输入文件 {input_path} 不存在。")
        input_dir = os.path.dirname(input_path)
        if input_dir and not os.path.exists(input_dir):
            os.makedirs(input_dir)
        if create_example_geojson(input_path):
            print("已创建示例GeoJSON文件，请修改后重新运行。")
        return False

    # 处理文件
    if params is None:
        params = get_default_flight_parameters()
    
    return geojson_to_dji_kmz(input_path, output_path, params)

if __name__ == "__main__":
    process_geojson_file()